package com.jms.mybatis.plus.proxy;

import com.jms.mybatis.plus.context.MyBatisContextImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperBeanProxy {

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(Class<T> mapperInterface) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] {mapperInterface}, new MapperBeanInvocationHandler(mapperInterface));
    }

    private static class MapperBeanInvocationHandler implements InvocationHandler {
        private final Class<?> mapperInterface;

        public MapperBeanInvocationHandler(Class<?> mapperInterface) {
            this.mapperInterface = mapperInterface;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object mapper = MyBatisContextImpl.getInstance().getMapper(mapperInterface);
            return method.invoke(mapper, args);
        }
    }
}
